<template>
    <div class="goods-add-form">
        <div class="section1">
            <div class="pro_info_title"
                style="text-align: center; display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <div style="font-size: 18px; font-weight: bold; color: #333;">
                    {{ sales_order.sale_order_name }}&nbsp;{{ sales_order.sale_order_code }}
                </div>
                <div style=" height: 40px;width: 250px; text-align: center;line-height: 40px;float: right;">
                    <el-button plain @click="handleEdit">编辑</el-button>
                    <el-button plain @click="handleDelete">删除</el-button>
                    <el-button plain @click="handleAudit">审核</el-button>
                </div>
            </div>

            <hr style="border: 0; height: 1px; background: #e0e0e0; margin: 10px 0 20px;">

            <table style="width: 100%; border-collapse: collapse; font-family: Arial, sans-serif;">
                <tbody>
                    <!-- 第一行 -->
                    <tr>
                        <td style="padding: 12px 15px; width: 15%; color: #666; font-weight: 500;">
                            客户名称</td>
                        <td style="padding: 12px 15px; width: 20%;">{{
                            sales_order.customer_name }}</td>
                        <td style="padding: 12px 15px; width: 15%; color: #666; font-weight: 500;">
                            联系人</td>
                        <td style="padding: 12px 15px; width: 20%;">{{
                            sales_order.contacts_name }}</td>
                        <td style="padding: 12px 15px; width: 15%; color: #666; font-weight: 500;">
                            联系电话</td>
                        <td style="padding: 12px 15px; width: 15%;">{{
                            sales_order.contacts_phone }}</td>
                    </tr>

                    <!-- 第二行 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            订单签订日期</td>
                        <td style="padding: 12px 15px;">{{ sales_order.sale_order_sign_time.replace('T', ' ') }}
                        </td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            订单交付日期</td>
                        <td style="padding: 12px 15px;">{{ sales_order.sale_order_deliver_time.replace('T', ' ') }}
                        </td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            销售负责人</td>
                        <td style="padding: 12px 15px;">{{ userValue(sales_order.sale_order_rep_id)
                        }}</td>
                    </tr>

                    <!-- 第三行 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            负责人部门</td>
                        <td style="padding: 12px 15px;">{{
                            deptValue(sales_order.sale_order_dept_id) }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            订单状态</td>
                        <td style="padding: 12px 15px;">{{ sales_order.status
                        }}</td>
                        <!-- <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            客户状态</td>
                        <td style="padding: 12px 15px;">{{
                            sales_order.sale_order_name }}</td> -->
                    </tr>

                    <!-- 第六行 - 创建信息 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            创建人</td>
                        <td style="padding: 12px 15px;">{{ sales_order.create_by }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            创建时间</td>
                        <td style="padding: 12px 15px;" colspan="3">{{ sales_order.create_time === 'null' ? '无' :
                            sales_order.create_time.replace('T', ' ')
                            }}</td>
                    </tr>

                    <!-- 第七行 - 修改信息 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">修改人</td>
                        <td style="padding: 12px 15px;">{{ sales_order.update_by === 'null' ? '暂无' :
                            sales_order.update_by }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">修改时间</td>
                        <td style="padding: 12px 15px;" colspan="3">
                            {{ sales_order.update_time === 'null' ? '暂无' : sales_order.update_time.replace('T', ' ') }}
                        </td>
                    </tr>

                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            审核人</td>
                        <td style="padding: 12px 15px;">{{ sales_order.sale_order_audit_by === 'null'
                            ? '暂无' : sales_order.sale_order_audit_by }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            审核时间</td>
                        <td style="padding: 12px 15px;" colspan="3">
                            {{ sales_order.sale_order_audit_time === 'null' ? '暂无' :
                                sales_order.sale_order_audit_time.replace('T', ' ') }}
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="section">
            <el-menu mode="horizontal" :default-active="activeMenu" @select="handleMenuSelect" class="inventory-menu"
                :ellipsis="false">
                <!-- <el-menu-item index="other">其他信息</el-menu-item> -->
                <el-menu-item index="details">销售明细</el-menu-item>
                <el-menu-item index="outbound">出库记录</el-menu-item>
                <el-menu-item index="returnOfGoods">退货记录</el-menu-item>
            </el-menu>
            <!-- 主内容区 -->

            <component :is="currentComponent" :key="sales_order.sale_order_code"
                :details-data="sales_order.sale_order_code" v-if="sales_order.sale_order_code" />
        </div>

        <!-- </div> -->
        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button @click="pro_sale_handleClose">关闭</el-button>
        </div>
    </div>

    <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
        <template #header>
            <div style="text-align: left; font-size: 16px; font-weight: bold;">
                审核
            </div>
        </template>
        <hr>
        <div style="text-align: left;padding: 10px 0px;">
            <p>审核结果</p>
            <div class="my-2 ml-4">
                <el-radio-group v-model="auditStatus">
                    <el-radio value="1">通过</el-radio>
                    <el-radio value="2">驳回</el-radio>
                </el-radio-group>
            </div>
            <div>
                <p>审核意见</p>
                <el-input v-model="auditOpinion" style="width: 350px;height: 90px;"
                    :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" placeholder="请输入" />
            </div>
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="updateAudit">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, inject, watch, toRaw, markRaw } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage, handleEdit, ElMessageBox, ElLoading } from 'element-plus';
import { Delete } from '@element-plus/icons-vue'
import { useStore } from 'vuex';
import details from './SalesOrdereInfo_details.vue'
import outbound from './SalesOrdereInfo_outbound.vue'
import returnOfGoods from './SalesOrdereInfo_returnOfGoods.vue';
import dayjs from 'dayjs'
export default {
    setup() {
        const sales_order = reactive({
            sale_order_id: "",//销售订单id
            sale_order_name: "",//销售订单名称
            sale_order_code: "",//销售订单编号
            customer_name: "",//客户名称
            customer_code: "",//客户编号
            contacts_name: "",//联系人名称
            contacts_phone: "",//联系人电话/联系方式
            sale_order_sign_time: "",//订单签订日期
            sale_order_deliver_time: "",//订单交付日期
            sale_order_rep_id: "",//销售订单负责人
            sale_order_dept_id: "",//销售部门
            sale_order_audit_by: "",//审核人
            sale_order_audit_time: "",//审核时间
            create_by: "",//创建人
            create_time: "",//创建时间
            update_by: "",//修改人
            update_time: "",//修改时间
            sale_order_audit_status: "",//审核状态
            sale_order_status: "",//出库状态
            status: ""
        })

        const userOptions = ref([])
        const deptOptions = ref([])
        const activeMenu = ref('details')
        const store = useStore()
        const router = useRouter()
        const centerDialogVisible = ref(false)
        const auditStatus = ref('1')
        const auditOpinion = ref('')
        const code = store.state.SalesOrderCode

        onMounted(() => {
            getUser()
            getDept()
            fillSalesOrder()
        })

        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function getDept() {
            axios.get("http://localhost:5181/api/Dept/DeptOpt", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function deptValue(row) {
            if (!row) return "无";
            const parentDept = deptOptions.value.find((dept) => dept.dept_id == row)
            return parentDept ? parentDept.dept_name : "无"
        }

        function userValue(row) {
            if (!row) return "无";
            const parentUser = userOptions.value.find((user) => user.user_id == row)
            return parentUser ? parentUser.user_name : "无"
        }

        function fillSalesOrder() {
            axios.get("http://localhost:5181/api/Sinv_Sale_Order/GetSinv_Sale_OrderByCode", {
                params: {
                    code: code
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                for (const key in sales_order) {
                    // 排除数字类型字段（如 user_id、dept_id）
                    if (key === 'sale_order_rep_id' || key === 'sale_order_dept_id') {
                        sales_order[key] = result.data[key]; // 保留数字类型
                    } else {
                        sales_order[key] = String(result.data[key]); // 其他字段转字符串
                    }
                }
                if (sales_order.sale_order_audit_status === '0') {
                    sales_order.status = '待审核';
                } else if (sales_order.sale_order_audit_status === '1') {
                    // 审核通过，显示出库状态
                    switch (sales_order.sale_order_status) {
                        case '0':
                            sales_order.status = '待出库';
                            break;
                        case '1':
                            sales_order.status = '部分出库';
                            break;
                        case '2':
                            sales_order.status = '全部出库';
                            break;
                        case '3':
                            sales_order.status = '部分退货';
                            break;
                        case '4':
                            sales_order.status = '全部退货';
                            break;
                        default:
                            sales_order.status = '未知出库状态';
                    }
                } else if (sales_order.sale_order_audit_status === '2') {
                    sales_order.status = '审核驳回';
                } else {
                    sales_order.status = '未知状态';
                }
            }).catch((err) => {
                console.info(err)
            });
        }


        const menuComponentMap = {
            // other: OtherInfo,
            details: details,
            outbound: outbound,
            returnOfGoods: returnOfGoods
            // store: StoreRecord,
            // visit: VisitRecord
        };

        // 当前显示的组件
        const currentComponent = ref(details);

        const handleMenuSelect = (index) => {
            console.info(sales_order.sale_order_code)
            activeMenu.value = index;
            currentComponent.value = menuComponentMap[index];

            // 可以在此处添加数据加载逻辑
        };

        // const detailsData = ref([]); // 存储明细数据

        //查询销售记录数据
        // async function fillSalesDetails() {
        //     try {
        //         const result = await axios.get("http://localhost:5181/api/Sinv_Sale_Order/GetSinv_Sale_Order_DetailsByCode", {
        //             params: { code: code },
        //             headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        //         });

        //         // 使用 Promise.all 等待所有 getInv_Stock 请求完成
        //         const detailsWithStock = await Promise.all(
        //             result.data.map(async (item) => {
        //                 const stock_numder = await getInv_Stock(item.pro_code);
        //                 return {
        //                     stock_name: item.pro_name,
        //                     stock_model: item.pro_model,
        //                     dict_code: item.measure_id,
        //                     sale_qty: item.pro_sale_qty,
        //                     stock_numder: stock_numder,
        //                     ...item
        //                 };
        //             })
        //         );
        //         detailsData.value = detailsWithStock;
        //     } catch (err) {
        //         detailsData.value = []
        //         console.error(err);
        //     }
        // }

        // //查询出库记录数据
        // function fillOutbound() {
        //     axios.get("http://localhost:5181/api/Sinv_Sale_Outbound/GetSinv_Sale_Outbound_Infos", {
        //         params: {
        //             currentPage: 0,
        //             pageSize: 0,
        //             customerName: '',
        //             orderCode: sales_order.sale_order_code
        //         }, headers: {
        //             authorization: `Bearer ${localStorage.getItem('token')}`
        //         }
        //     }).then((result) => {
        //         detailsData.value = result.data
        //     }).catch((err) => {
        //         detailsData.value = []
        //         console.info(err)
        //     });
        // }

        // async function getInv_Stock(row) {
        //     try {
        //         const result = await axios.get("http://localhost:5181/api/Db_warehouse/GetInv_StockByCode", {
        //             params: { code: row },
        //             headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        //         });
        //         return result.data.stock_numder;
        //     } catch (err) {
        //         console.error(err);
        //         return null;
        //     }
        // }
        const closeTab = inject('closeTab'); // 注入关闭方法

        function pro_sale_handleClose() {
            const targetPath = "/main/Sinv/SalesOrder";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "销售订单",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        }

        function handleDelete() {
            if (sales_order.sale_order_audit_status == "1") {
                ElMessage.warning('审核通过后不允许进行删除！')
                return
            }
            ElMessageBox.confirm(
                '此操作将删除' + sales_order.sale_order_code + '销售订单，是否继续？',
                '警告',
                {
                    type: 'warning',
                    icon: markRaw(Delete),
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }
            )
                .then(() => {
                    const loadingInstance = ElLoading.service({
                        lock: true,
                        text: '正在删除中...',
                        background: 'rgba(0, 0, 0, 0.7)',
                    });
                    axios.put("http://localhost:5181/api/Sinv_Sale_Order/Sinv_Sale_OrderDel", {
                        sale_order_id: sales_order.sale_order_id,
                        del_flag: '1'
                    }, {
                        headers: {
                            authorization: `Bearer ${localStorage.getItem('token')}`
                        }
                    }).then((result) => {
                        if (result.data > 0) {
                            ElMessage.success('删除成功！')
                            pro_sale_handleClose()
                        } else {
                            ElMessage({
                                type: 'danger',
                                message: '销售订单删除失败！'
                            });
                        }
                    }).catch((err) => {
                        console.info(err)
                    }).finally(() => {
                        loadingInstance.close();
                    })
                })
                .catch(() => {
                    ElMessage.info('已取消删除')
                })
        }

        function handleEdit() {
            if (sales_order.sale_order_audit_status == "1") {
                ElMessage.warning('审核通过后不允许再次编辑！')
                return
            }
            store.commit("SalesOrderCode", code)
            router.push("/main/Sinv/SalesOrderUpdate")
        }

        function handleAudit() {
            if (sales_order.sale_order_audit_status != '0') {
                ElMessage.warning('已审核过的订单不允许再次审核！')
                return
            }
            centerDialogVisible.value = true
        }

        function updateAudit() {
            const loadingInstance = ElLoading.service({
                lock: true,
                text: '正在审核中...',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            axios.put("http://localhost:5181/api/Sinv_Sale_Order/Sinv_Sale_OrderAuditUpdate", {
                sale_order_id: sales_order.sale_order_id,
                sale_order_audit_by: localStorage.getItem('userLName'),
                sale_order_audit_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                sale_order_audit_opinion: auditOpinion.value,
                sale_order_audit_status: auditStatus.value
            }, {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    if (auditStatus.value == '1') {
                        ElMessage.success('审核通过')
                    } else if (auditStatus.value == '2') {
                        ElMessage.warning('审核已被驳回！')
                    }
                    close()
                    pro_sale_handleClose()
                } else {
                    ElMessage({
                        type: 'danger',
                        message: '销售订单审核失败！'
                    });
                }
            }).catch((err) => {
                console.info(err)
            }).finally(() => {
                loadingInstance.close();
            })
        }

        //取消审核按钮
        function close() {
            centerDialogVisible.value = false
            auditStatus.value = "1"
            auditOpinion.value = ""
        }

        return {
            sales_order, userOptions, deptOptions, deptValue, userValue, activeMenu, handleMenuSelect, currentComponent,
            pro_sale_handleClose, handleDelete, handleEdit, centerDialogVisible, auditStatus, auditOpinion, handleAudit,
            updateAudit, close
        }
    }
}
</script>

<style scoped>
.section {
    padding: 20px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}

.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section1 {
    padding: 20px;
    height: 390px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.pro_info_title {
    text-align: center;
    width: 1205px;
    height: 40px;
}
</style>